package com.fight.strive.sys.modules.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.fight.strive.sys.modules.auth.dto.StriveAuthInfo;
import com.fight.strive.sys.modules.auth.service.StriveAuthService;
import com.fight.strive.sys.modules.exception.exceptions.StriveInvalidTokenException;
import com.fight.strive.sys.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;


@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private StriveAuthService striveAuthService;

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime",
                LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "updateTime",
                LocalDateTime::now, LocalDateTime.class);
        try {
            StriveAuthInfo striveAuthInfo = striveAuthService.getCurrentAuth();
            if (ObjectUtils.notNull(striveAuthInfo)) {
                this.strictInsertFill(metaObject, "createUserId",
                        Long.class, striveAuthInfo.getUser().getId());
                this.strictInsertFill(metaObject, "updateUserId",
                        Long.class, striveAuthInfo.getUser().getId());
            }
        } catch (StriveInvalidTokenException ignored) {
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        metaObject.setValue("updateTime", LocalDateTime.now());
        try {
            StriveAuthInfo striveAuthInfo = striveAuthService.getCurrentAuth();
            if (ObjectUtils.notNull(striveAuthInfo)) {
                metaObject.setValue("updateUserId",
                        striveAuthInfo.getUser().getId());
            }
        } catch (StriveInvalidTokenException ignored) {
        }
    }
}
